package com.java.jvm.bytecode.instrument;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * 对传入的类进行字节码增强转换，但是增强过程还是要
 * 借助asm或Javassist技术,本次实验借助Javassist技术
 */
public class DefaultClassTransformer implements ClassFileTransformer {
    /**
     * 在Transform方法中对指定类进行功能增强，本质上就是修改目标类型字节码
     * @param loader
     * @param className
     * @param classBeingRedefined
     * @param protectionDomain
     * @param classfileBuffer
     * @return
     * @throws IllegalClassFormatException
     */
    @Override
    public byte[] transform(ClassLoader loader,
                            String className,
                            Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain,
                            byte[] classfileBuffer)
            throws IllegalClassFormatException {
        if (!className.equals("com/java/jvm/bytecode/service/CycleService")) {
            return null; // 如果返回null则字节码不会被修改
        }
        try {
            //1.获取目标类(目标类的信息会封装到CtClass对象中)
            ClassPool classPool=ClassPool.getDefault();
            CtClass ctClass = classPool
                    .get("com.java.jvm.bytecode.service.CycleService");
            //2.获取目标方法信息
            CtMethod targetMethod = ctClass.getDeclaredMethod("doCycle");
            //3.执行方法功能增强
            targetMethod.insertBefore("{System.out.println(\"start\");}");
            targetMethod.insertAfter("{System.out.println(\"end\");}");
            return ctClass.toBytecode();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
